<template>
  <div class="app-container">
    <el-row :gutter="20" class="div-height-left">
      <el-col v-if="userInfo.userId === '1'" :span="4" class="div-height-left">
        <sys-org-tree @treeClick="treeClick"/>
      </el-col>
      <el-col :span="userInfo.userId === '1' ? 20 : 24" :xs="24">
        <div class="search-container">
          <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams"
                   label-width="120px">
            <el-form-item label="手术操作代码" prop="operationCode">
              <el-input v-model="queryParams.operationCode" clearable placeholder="请输入手术操作代码"
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="手术操作名称" prop="operationName">
              <el-input v-model="queryParams.operationName" clearable placeholder="请输入手术操作名称"
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="手术操作等级" prop="operationScale">
              <el-select v-model="queryParams.operationScale" class="width-120" clearable
                         placeholder="请选择手术等级" @change="getList">
                <el-option v-for="dict in dictDataMap['operation_grade']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item label="手术状态" prop="operationFlag">
              <el-radio-group v-model="queryParams.operationFlag" @change="handleQuery">
                <el-radio value="">全部</el-radio>
                <el-radio v-for="dict in dictDataMap['sys_normal_disable']" :key="dict.dictValue"
                          :value="dict.dictValue">{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="mr20" style="float: right">
              <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
            </div>
          </el-form>
        </div>
        <el-row :gutter="10" class="mb8" style="margin-right: 180px">
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:operationDict:add']" :disabled="!queryParams.orgId" plain
                       type="primary" @click="handleAdd">
              <template #icon>
                <i-ep-plus/>
              </template>
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:operationDict:edit']" :disabled="single" plain type="success"
                       @click="handleUpdate">
              <template #icon>
                <i-ep-edit/>
              </template>
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:operationDict:remove']" :disabled="multiple" plain type="danger"
                       @click="handleDelete">
              <template #icon>
                <i-ep-delete/>
              </template>
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:operationDict:export']" plain type="warning"
                       @click="handleExport">
              <template #icon>
                <i-ep-download/>
              </template>
              导出
            </el-button>
          </el-col>
        </el-row>

        <el-table v-adaptive :border="true" :data="operationDictList" :header-cell-style="$headerCellStyle" :stripe="true"
                  highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column :align="'center'" type="selection" width="55"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="手术操作代码"
                           prop="operationCode"/>
          <el-table-column :align="'left'" :show-overflow-tooltip="true" label="手术操作名称"
                           prop="operationName"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="手术等级" prop="operationScale">
            <template #default="scope">
              <dict-data-tag slot="reference" v-popover:popover :options="dictDataMap['operation_grade']"
                             :value="scope.row.operationScale"/>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="拼音码" prop="inputCode"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="单位" prop="unit"
                           width="80"/>
          <!-- <el-table-column :align="'center'" :show-overflow-tooltip="true" label="手术状态" prop="operationFlag"
                           width="80">
            <template #default="scope">
              <el-switch v-model="scope.row.operationFlag" active-value="0" inactive-value="1"
                         @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column> -->
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="是否已对照" prop="clinicId"
                           width="100">
            <template #default="scope">
              <el-tag :type="scope.row.clinicId != null ? 'success' : 'warning'">
                {{ scope.row.clinicId != null ? '已对照' : '未对照' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注信息" prop="remark"/>
          <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作" width="260">
            <template #default="scope">
              <el-button v-hasPerm="['base:clinicItemDict:addControl']" type="success"
                         @click="addControl(scope.row)">
                <template #icon>
                  <i-ep-edit/>
                </template>
                添加对照
              </el-button>
              <el-button v-hasPerm="['base:operationDict:edit']" type="success"
                         @click="handleUpdate(scope.row)">
                <template #icon>
                  <i-ep-edit/>
                </template>
                修改
              </el-button>
              <el-button v-hasPerm="['base:operationDict:remove']" type="danger"
                         @click="handleDelete(scope.row)">
                <template #icon>
                  <i-ep-delete/>
                </template>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                    :total="total" @pagination="getList"/>
      </el-col>
    </el-row>
    <!-- 添加或修改手术操作字典对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="900px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="手术操作代码" prop="operationCode">
              <el-input v-model="form.operationCode" placeholder="请输入手术操作代码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手术操作名称" prop="operationName">
              <el-input v-model="form.operationName" placeholder="请输入手术操作名称" @input="itemNameInput"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手术等级" prop="operationScale">
              <el-select v-model="form.operationScale" filterable placeholder="请选择手术等级"
                         style="width: 100%;">
                <el-option v-for="dict in dictDataMap['operation_grade']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拼音码" prop="inputCode">
              <el-input v-model="form.inputCode" placeholder="请输入拼音码"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="单位">
              <el-input v-model="form.unit" placeholder="请输入单位"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手术状态">
              <el-input v-model="form.operationFlag" placeholder="请输入手术状态"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注信息" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入内容" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
      </template>
    </el-dialog>
    <control-operation-dialog ref="controlOperationDialogRef" @saveOperaControl="saveOperaControl"
                              @selectClinicList="getList"/>

  </div>
</template>

<script lang="ts" setup>
import {
  addOperationDict,
  delOperationDict,
  getOperationDict,
  selectPageOperationDict,
  updateOperationDict
} from "@/api/base/operationDict";
import {firstLetterResult} from "@/utils/pinyin"
import controlOperationDialog from "@/views/base/operationDict/controlOperationDialog.vue";
import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user"

const formRef = ref()
const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook();
const dictDataMap = ref(dictStore.isTypeGetData('operation_grade', 'sys_normal_disable'))
const controlOperationDialogRef = ref()
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
// 按钮loading
const buttonLoading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 手术操作字典表格数据
const operationDictList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 查询参数
const queryParamsRef = ref()
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  operationCode: undefined,
  operationName: undefined,
  operationScale: undefined,
  inputCode: undefined,
  clinicId: undefined,
  unit: undefined,
  operationFlag: '',
  orgId: undefined,
})
// 表单参数
const form = ref<any>({})
// 表单校验
const rules = ref({
  operationDictId: [
    {required: true, message: "不能为空", trigger: "blur"}
  ],
  operationCode: [
    {required: true, message: "手术操作代码不能为空", trigger: "blur"}
  ],
  operationName: [
    {required: true, message: "手术操作名称不能为空", trigger: "blur"}
  ],
  operationScale: [
    {required: true, message: "手术等级不能为空", trigger: "blur"}
  ],
  inputCode: [
    {required: true, message: "拼音码不能为空", trigger: "blur"}
  ],
  clinicId: [
    {required: true, message: "诊疗项目ID不能为空", trigger: "blur"}
  ],
  unit: [
    {required: true, message: "单位不能为空", trigger: "blur"}
  ],
  operationFlag: [
    {required: true, message: "手术状态不能为空", trigger: "blur"}
  ],
  orgId: [
    {required: true, message: "机构ID不能为空", trigger: "blur"}
  ],
})
if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId
  getList()
}

/** 添加对照 */
function addControl(row) {
  row.itemCode = row.operationCode
  row.itemName = row.itemName || row.operationName
  row.orgId = queryParams.value.orgId
  controlOperationDialogRef.value.addControlDialogShow(row)
}

/** 查询手术操作字典列表 */
function getList() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择左侧所属机构后查询")
  }
  selectPageOperationDict(queryParams.value).then((response: any) => {
    operationDictList.value = response.rows;
    total.value = response.total;
  });
}

/** 左侧科室树节点点击事件 */
function treeClick(obj) {
  queryParams.value.orgId = obj.id
  getList()
}

/** 项目名称输入框改变事件 设置拼音码*/
function itemNameInput(value) {
  if (value) {
    form.value.inputCode = firstLetterResult(value)
  } else {
    form.value.inputCode = ""
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    operationDictId: undefined,
    operationCode: undefined,
    operationName: undefined,
    operationScale: undefined,
    inputCode: undefined,
    clinicId: undefined,
    unit: undefined,
    operationFlag: undefined,
    orgId: queryParams.value.orgId,
    delFlag: undefined,
    createBy: undefined,
    createTime: undefined,
    updateBy: undefined,
    updateTime: undefined,
    remark: undefined
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.operationDictId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加手术操作字典";
}

// 用户状态修改
function handleStatusChange(row) {
  let text = row.operationScale === "0" ? "启用" : "停用";
  ElMessageBox.confirm('确认要"' + text + '"名称为："' + row.operationName + '"手术？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    updateOperationDict(row).then(() => {
      ElMessage.success(text + "成功");
    })
  }).catch(function () {
    row.operationScale = row.operationScale === "0" ? "1" : "0";
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const operationDictId = row.operationDictId || ids.value
  getOperationDict(operationDictId).then(response => {
    open.value = true;
    form.value = response.data;
    title.value = "修改手术操作字典";
  });
}

/** 修改对照 */
function saveOperaControl(form) {
  updateOperationDict(form.value).then(_response => {
    ElMessage.success("对照成功");
    controlOperationDialogRef.value.cancel()
  })
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.operationDictId != null) {
        updateOperationDict(form.value).then(_response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addOperationDict(form.value).then(_response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const operationDictIds = row.operationDictId || ids;
  ElMessageBox.confirm('是否确认删除手术操作字典编号为"' + operationDictIds + '"的数据项？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delOperationDict(operationDictIds).then(() => {
      getList();
      ElMessage.success("删除成功");
    })
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  // download('base/operationDict/export', {
  //     ...queryParams
  // }, `operationDict_${new Date().getTime()}.xlsx`)
}
</script>
<script lang="ts">
export default {
  name: "OperationDict"
};
</script>
